package com.example.cloudmusic.home.repository

import com.example.cloudmusic.home.model.*
import com.example.cm_network.ApiService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

/**
 * 首页数据仓库实现类
 */
class HomeRepositoryImpl(
    private val apiService: ApiService,
    private var dataSourceType: DataSourceType = DataSourceType.MOCK
) : HomeRepository {

    private val dataSource: DataSourceStrategy
        get() = DataSourceFactory.create(dataSourceType)

    /**
     * 切换数据源类型
     */
    fun switchDataSource(type: DataSourceType) {
        dataSourceType = type
    }

    /**
     * 获取当前数据源类型
     */
    fun getCurrentDataSourceType(): DataSourceType = dataSourceType

    /**
     * 获取首页所有数据
     */
    override suspend fun getHomeData(): Result<List<HomeItem>> = withContext(Dispatchers.IO) {
        try {
            val homeItems = mutableListOf<HomeItem>()
            
            // 添加轮播图
            val bannerResult = getBanners()
            if (bannerResult.isSuccess) {
                homeItems.add(HomeItem.BannerSection(
                    id = "banner_section",
                    items = bannerResult.getOrThrow()
                ))
            }

            // 添加个人收藏歌单
            val personalPlaylistsResult = getPersonalPlaylists()
            if (personalPlaylistsResult.isSuccess) {
                homeItems.add(HomeItem.PersonalPlaylistSection(
                    id = "personal_playlist",
                    title = "我的收藏",
                    items = personalPlaylistsResult.getOrThrow()
                ))
            }


            
            // 添加推荐歌曲
            val musicsResult = getRecommendedMusics()
            if (musicsResult.isSuccess) {
                homeItems.add(HomeItem.RecommendedMusicsSection(
                    id = "recommended_musics",
                    title = "为你推荐",
                    musics = musicsResult.getOrThrow()
                ))
            }
            
            // 添加艺人区块
            val artistsResult = getHotArtists()
            if (artistsResult.isSuccess) {
                homeItems.add(HomeItem.ArtistSection(
                    id = "popular_artists",
                    title = "热门艺人",
                    artists = artistsResult.getOrThrow()
                ))
            }

            // 添加推荐歌单
            val playlistsResult = getRecommendedPlaylists()
            if (playlistsResult.isSuccess) {
                homeItems.add(HomeItem.RecommendedPlaylistsSection(
                    id = "recommended_playlists",
                    title = "推荐歌单",
                    playlists = playlistsResult.getOrThrow()
                ))
            }


            // 添加音乐风格区块
            val musicStylesResult = getMusicStyles()
            if (musicStylesResult.isSuccess) {
                homeItems.add(HomeItem.MusicStyleSection(
                    id = "music_style",
                    title = "音乐风格",
                    musics = musicStylesResult.getOrThrow()
                ))
            }
            
            Result.success(homeItems)
        } catch (e: Exception) {
            Result.failure(e)
        }
    }
    
    /**
     * 获取轮播图数据
     */
    override suspend fun getBanners(): Result<List<Banner>> = dataSource.getBanners()
    
    /**
     * 获取推荐歌单
     */
    override suspend fun getRecommendedPlaylists(): Result<List<Playlist>> = dataSource.getRecommendedPlaylists()
    
    /**
     * 获取热门艺人
     */
    override suspend fun getHotArtists(): Result<List<Artist>> = dataSource.getHotArtists()
    
    /**
     * 获取个人歌单
     */
    override suspend fun getPersonalPlaylists(): Result<List<Playlist>> = dataSource.getPersonalPlaylists()
    
    /**
     * 获取音乐风格
     */
    override suspend fun getMusicStyles(): Result<List<MusicStyle>> = dataSource.getMusicStyles()
    
    /**
     * 获取推荐歌曲
     */
    override suspend fun getRecommendedMusics(): Result<List<Music>> = dataSource.getRecommendedMusics()

    /**
     * 生成模拟歌单数据
     */
    private fun getMockPlaylists(count: Int): List<Playlist> {
        val titles = listOf(
            "听歌的人不寂寞", "好听的歌曲说唱版", "热恋的旋律，不一样的感受",
            "我喜欢的音乐", "周杰伦歌单", "适合深夜的轻音乐", "全世界失眠", "说谎",
            "我的名字", "情话", "感谢你曾来过", "起风了", "一路向北"
        )

        val artists = listOf(
            "林俊杰", "周杰伦", "邓紫棋", "陈奕迅", "五月天", "薛之谦", "阿肆", "TFBOYS"
        )

        val items = mutableListOf<Playlist>()
        repeat(count) { index ->
            items.add(
                Playlist(
                    id = "playlist_$index",
                    title = titles.random(),
                    artist = artists.random(),
                    imageUrl = "https://p1.music.126.net/wUog39IHoJb76pL0AVCFNQ==/109951165348116023.jpg?param=130y130",
                    playCount = (50000..5000000).random().toLong(),
                    description = "精选歌单，为您推荐",
                    musics = getMockMusics(10)
                )
            )
        }
        return items
    }

    /**
     * 生成模拟歌曲数据
     */
    private fun getMockMusics(count: Int): List<Music> {
        val titles = listOf(
            "晴天", "稻香", "倒数", "一路向北", "七里香", "不能说的秘密",
            "离开地球表面", "天黑黑", "说好的幸福呢", "听妈妈的话",
            "算什么男人", "星晴", "修炼爱情", "爱笑的眼睛", "不爱我就拉倒"
        )

        val artists = listOf(
            "周杰伦", "林俊杰", "邓紫棋", "陈奕迅", "五月天", "薛之谦", "张学友", "王菲"
        )

        val albums = listOf(
            "叶惠美", "魔杰座", "新地球", "十一月的肖邦", "依然范特西", "跨时代",
            "七里香", "八度空间", "Jay", "范特西", "哎呦不错哦"
        )

        val types = listOf("流行", "民谣", "摇滚", "电子", "嘻哈", "爵士", "古典")

        val musics = mutableListOf<Music>()
        repeat(count) { index ->
            musics.add(
                Music(
                    id = "music_$index",
                    title = titles.random(),
                    artist = artists.random(),
                    album = albums.random(),
                    imageUrl = "https://p1.music.126.net/wUog39IHoJb76pL0AVCFNQ==/109951165348116023.jpg?param=130y130",
                    duration = (180000..300000).random().toLong(),
                    playUrl = "https://example.com/music/song_$index.mp3",
                    isVip = index % 5 == 0,
                    isFavorite = index % 3 == 0,
                    type = types.random()
                )
            )
        }
        return musics
    }
}